define(function (require, exports, module) {
    'use strict';
    var rk = require('rk');
    var UE = require('lib/ueditor/ueditor.all');

    $.widget('rk.headlineDialogCtrl', $.rk.oaDialogCtrl, {
        _create: function () {
            var me = this;
            var elem = me.element;
            var temp = require('page/tmpl/index/prm/tpl_prm_headline_create.tpl');
            var html = rk.templateText(temp, SESSION);
            elem.html(html);

            elem.find('[act="headline-dep"]').multiselect({
                header: true,
                multiple: true,
                selectedList: 8,
                autoOpen: false,
                checkAllText: '全选',
                uncheckAllText: '全不选',
                noneSelectedText: '请选择' + SESSION.keywords.partner,
                selectedText: '已选择 # 项',
                classes: '',
                position: ({
                    my: "left+0 top", //ZL: +15
                    at: "left bottom",
                    collision: 'flipfit',
                    within: window
                })
            });

            var footer = me.getFooter();
            me.getBtn('draft').on('click', $.proxy(me.draftClicked, me));
            me.getBtn('ok').on('click', $.proxy(me.okClicked, me));
            footer.find('*[act="cancel"]').on('click', $.proxy(me.cancelClicked, me));

            var editor = new UE.ui.Editor({initialFrameHeight: 300, initialFrameWidth: 770});
            editor.render('headlineEditor');
            me.editor = editor;
        },
        _init: function () {
            var me = this;
            var elem = me.element;
            me._initData();
        },
        _initData: function () {
            var me = this, elem = me.element, opt = this.options;
            var param = {};
            var url = opt.contentId ? "/json/oa_prm_content/to-update-content.action" : "/json/oa_prm_content/init-space-partners.action";

            rk.post(url, {contentId: opt.contentId}, function (json) {
                if (json.status === 0) {
                    var html = template.compile('{{each partners as partner i}}<option value="{{partner.id}}">{{partner.name}}</option>{{/each}}')(json.data)
                    elem.find("[act='headline-dep']")
                        .html(html)
                        .val(($.isArray(json.data.checkedIds) && json.data.checkedIds.length) ? json.data.checkedIds.sort() : -1)
                        .multiselect('refresh');
                    if (opt.contentId) {
                        elem.find("input[name=title]").val(json.data.partnerContent.title);
                        me.editor.setContent(json.data.partnerContent.content);
                        rk.repositionDialog();
                    }
                } else {
                    rk.noticeError(rk.i18n('ERROR_SYSTEM'));
                }
            });
        },
        draftClicked: function () {
            var me = this;
            var elem = me.element;
            me._doSave(0);//保存
        },
        okClicked: function () {
            var me = this;
            var elem = me.element;
            me._doSave(1);//保存
        },
        cancelClicked: function () {
            var me = this;
            var elem = me.element;
            me.closeMe();//关闭
        },
        _doSave: function (publishFlg) {
            var me = this,
                elem = this.element,
                opt = this.options;
            var editor = me.editor;
            editor.sync("headlineSaveForm");
            var form = elem.find("[act='headline_add_form']");
            var formData = form.serializeArray();
            var params = {};
            $.each(formData, function (i, json) {
                if (json.name === "partnerId" && json.value) {
                    json.value = $.map(elem.find('[act="headline-dep"]').val(), function (v) {
                        return v;
                    }).join(',');
                    params["partnerIds"] = json.value;
                    return true;
                }
                params["partnerContent." + json.name] = json.value;
            });
            if (publishFlg && !params["partnerIds"]) {
                rk.noticeError('请选择' + SESSION.keywords.partner);
                return;
            }
            if (!params["partnerContent.title"]) {
                rk.noticeError(rk.i18n('ANNOUNCEMENT_1'));
                return;
            }
            if (!editor.hasContents()) {
                rk.noticeError(rk.i18n('ANNOUNCEMENT_2'));
                return;
            }
            var content = editor.getContent();
            if (content.length > 8000000) {
                rk.noticeError(rk.i18n('ANNOUNCEMENT_3'));
                return;
            }
            var url = "/json/oa_prm_content/save-content.action";
            if (opt.contentId) {
                params["partnerContent.id"] = opt.contentId;
                url = "/json/oa_prm_content/update-content.action";
            }
            params["partnerContent.publishFlg"] = publishFlg;
            var $btn1 = me.getBtn('draft'),
                $btn2 = me.getBtn('ok');
            $btn1.beLoading();
            $btn2.beLoading();
            rk.post(url, params, function (json) {
                if (json.status === 0) {
                    //panel 同步加载出问题，只能异步加载
                    require.async(['./prmHeadlineCtrl.js'], function (c) {
                        $("#index_prm_panel").prmHeadlineCtrl();
                        me.closeMe();
                    });
                    rk.noticeSuccess(rk.i18n('OPERATE_SUCCESS'));
                } else if (json.status === 100000) {
                    //系统错误
                    rk.noticeError(rk.i18n('ERROR_SYSTEM'));
                    $btn1.beLoading('delay');
                    $btn2.beLoading('delay');
                }
            });
        }
    });
});
